package com.scsj.supermarket.view.activity.settingmodel;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.orhanobut.logger.Logger;
import com.scsj.supermarket.Manifest;
import com.scsj.supermarket.R;
import com.scsj.supermarket.config.RxSPConfig;
import com.scsj.supermarket.customview.imagespickers.GlideLoader;
import com.scsj.supermarket.utils.CropCircleTransformation;
import com.scsj.supermarket.utils.GlideImageLoader;
import com.scsj.supermarket.utils.SkipUtils;
import com.scsj.supermarket.utils.ToastMiddleUtils;
import com.scsj.supermarket.view.activity.baseactivitymodel.BaseActivity;
import com.vondear.rxtools.RxPermissionsTool;
import com.vondear.rxtools.RxPhotoTool;
import com.vondear.rxtools.RxSPTool;
import com.vondear.rxtools.view.dialog.RxDialogChooseImage;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import static com.vondear.rxtools.view.dialog.RxDialogChooseImage.LayoutType.TITLE;

/**
 * 个人信息
 */
public class PersonalInformationActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout icon_rl, user_name_rl, nickname_rl, gender_rl, data_of_birth_rl;
    private Uri resultUri;
    private ImageView icon_iv;
    private TextView nickname_tv, sex_tv, data_of_birth_tv, username_tv;

    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_personal_information);
        initToolbar();
        setToolbarTitle("个人信息");
        hasBack(true);
    }

    @Override
    protected void initView() {
        icon_rl = findViewById(R.id.icon_rl);
        icon_iv = findViewById(R.id.icon_iv);
        username_tv = findViewById(R.id.username_tv);
        user_name_rl = findViewById(R.id.user_name_rl);
        nickname_rl = findViewById(R.id.nickname_rl);
        gender_rl = findViewById(R.id.gender_rl);
        data_of_birth_rl = findViewById(R.id.data_of_birth_rl);
        nickname_tv = findViewById(R.id.nickname_tv);
        sex_tv = findViewById(R.id.sex_tv);
        data_of_birth_tv = findViewById(R.id.data_of_birth_tv);
    }

    @Override
    protected void initListener() {
        icon_rl.setOnClickListener(this);
        user_name_rl.setOnClickListener(this);
        nickname_rl.setOnClickListener(this);
        gender_rl.setOnClickListener(this);
        data_of_birth_rl.setOnClickListener(this);
        sex_tv.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        Resources r = this.getResources();
        resultUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + r.getResourcePackageName(R.drawable.ic_launcher_background) + "/"
                + r.getResourceTypeName(R.drawable.ic_launcher_background) + "/"
                + r.getResourceEntryName(R.drawable.ic_launcher_background));

        if (!TextUtils.isEmpty(RxSPTool.getString(this, RxSPConfig.USER_AVATAR))) {
            Glide.with(this).load(RxSPTool.getString(this, RxSPConfig.USER_AVATAR)).into(icon_iv);
        }
        if (!TextUtils.isEmpty(RxSPTool.getString(this, RxSPConfig.USER_NAME))) {
            username_tv.setText(RxSPTool.getString(this, RxSPConfig.USER_NAME));
        }
        if (!TextUtils.isEmpty(RxSPTool.getString(this, RxSPConfig.USER_NICKNAME))) {
            username_tv.setText(RxSPTool.getString(this, RxSPConfig.USER_NICKNAME));
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.icon_rl:
                RxPermissionsTool.with(this)
                        .addPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .addPermission(android.Manifest.permission.CAMERA)
                        .initPermission();
                initDialogChooseImage();
                break;
            case R.id.user_name_rl:
                SkipUtils.toChangeNickName(this);
                ToastMiddleUtils.ToastMiddle(this, "用户名不支持修改哟~");
                break;
            case R.id.nickname_rl:
                SkipUtils.toChangeNickName(this);
                break;
            case R.id.gender_rl:
                SkipUtils.toChangeSex(this);
                break;
            case R.id.data_of_birth_rl:
                datePicker();
                break;

        }
    }

    private void initDialogChooseImage() {
        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(this, TITLE);
        dialogChooseImage.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
//                    RxPhotoTool.cropImage(ActivityUser.this, );// 裁剪图片
                    initUCrop(data.getData());
                }

                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                   /* data.getExtras().get("data");*/
//                    RxPhotoTool.cropImage(ActivityUser.this, RxPhotoTool.imageUriFromCamera);// 裁剪图片
                    initUCrop(RxPhotoTool.imageUriFromCamera);
                }

                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                Glide.with(this).
                        load(RxPhotoTool.cropImageUri).
                        diskCacheStrategy(DiskCacheStrategy.RESULT).
                        bitmapTransform(new CropCircleTransformation(this)).
                        thumbnail(0.5f).
                        placeholder(R.drawable.ic_launcher_background).
                        priority(Priority.LOW).
                        error(R.drawable.ic_launcher_background).
                        fallback(R.drawable.ic_launcher_background).
                        into(icon_iv);
//                RequestUpdateAvatar(new File(RxPhotoTool.getRealFilePath(mContext, RxPhotoTool.cropImageUri)));
                break;

            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    roadImageView(resultUri, icon_iv);
                    RxSPTool.putContent(this, "AVATAR", resultUri.toString());
                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                break;
            case 0://修改昵称
                if(resultCode == Activity.RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    nickname_tv.setText(bundle.getString("nickname"));
                }
                break;
            case 1:
                Bundle bundle1 = data.getExtras();
                sex_tv.setText(bundle1.getString("sex"));
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);

        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));

        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.colorPrimary));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.colorPrimaryDark));
        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
        //options.setOvalDimmedLayer(true);
        //设置是否展示矩形裁剪框
        // options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);
        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

    //从Uri中加载图片 并将其转化成File文件返回
    private File roadImageView(Uri uri, ImageView imageView) {
        Glide.with(this).
                load(uri).
                diskCacheStrategy(DiskCacheStrategy.RESULT).
                bitmapTransform(new CropCircleTransformation(this)).
                thumbnail(0.5f).
                placeholder(R.drawable.ic_launcher_background).
                priority(Priority.LOW).
                error(R.drawable.ic_launcher_background).
                fallback(R.drawable.ic_launcher_background).
                into(imageView);

        return (new File(RxPhotoTool.getImageAbsolutePath(this, uri)));
    }

    /**
     * 日期选择
     */
    private void datePicker() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        //正确设置方式 原因：注意事项有说明
        startDate.set(1950, 0, 1);
        endDate.set(2200, 11, 31);
        Calendar calendar = Calendar.getInstance(java.util.TimeZone.getTimeZone("GMT+08:00"));
        calendar.set(Calendar.MINUTE, 0);
        //设置默认当前的时间
//        String title = "选择时间";

        new TimePickerView.Builder(mContext, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中时间回调
                SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
                Logger.d(date);
                String formatData = format.format(date);
                Logger.d(formatData);
                data_of_birth_tv.setText(formatData);
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)
                .setContentSize(20)
                .setDividerColor(Color.DKGRAY)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)//设置起止时间
                .build()
                .show();
    }
}
